package com.shengyuan.manage_os.old.ying.erpm;

import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;

import com.shengyuan.manage_os.R;
import com.shengyuan.manage_os.im.ui.settings.SettingsActivity;
import com.shengyuan.manage_os.old.ying.boce.jsy.AdminPicForceHandlerTask;
import com.shengyuan.manage_os.old.ying.boce.jsy.UpdateManager;
import com.shengyuan.manage_os.old.ying.boce.task.GenericTask;
import com.shengyuan.manage_os.old.ying.boce.task.TaskAdapter;
import com.shengyuan.manage_os.old.ying.boce.task.TaskListener;
import com.shengyuan.manage_os.old.ying.boce.task.TaskParams;
import com.shengyuan.manage_os.old.ying.boce.task.TaskResult;
import com.shengyuan.manage_os.old.ying.erpm.device.BlueToothService;
import com.shengyuan.manage_os.old.ying.erpm.device.BlueToothService.OnReceiveDataHandleEvent;
import com.shengyuan.manage_os.old.ying.erpm.device.DeviceListActivity;
import com.shengyuan.manage_os.old.ying.erpm.tasks.SubmitUpdateTask;
import com.shengyuan.manage_os.old.ying.erpm.tasks.Submit_System_Setting_Data_Task;
import com.shengyuan.manage_os.old.ying.erpm.util.Utility;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;

import static com.shengyuan.manage_os.old.ying.erpm.SettingActivity.InitGoldelData;

public class Actual_System_Setting extends PreferenceActivity 
	implements OnSharedPreferenceChangeListener {
	public static Actual_System_Setting Instance;
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
	private static String  CITY = "天津";
	

	public static BlueToothService mBTService = null; 
	public Boolean SUCCESS_CONNECT = false ;
	SharedPreferences  sp;
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Instance = this;
		addPreferencesFromResource(R.xml.systemsetting);
		sp = PreferenceManager.getDefaultSharedPreferences(this); 
		//sp.registerOnSharedPreferenceChangeListener(this); 
		Boolean printerInfo = sp.getBoolean("title_form_setting_table_lixian", false); 
		if (mBTService==null) {
			mBTService = new BlueToothService(this, mhandler); 
		}
		mBTService.setOnReceive(new OnReceiveDataHandleEvent() {
			@Override
			public void OnReceive(BluetoothDevice device) {
				// TODO Auto-generated method stub
				if (device != null) {
//					mNewDevicesArrayAdapter.add(device.getName() + "\n"
//							+ device.getAddress());
				} else {
					mBTService.StopScan();
				}
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (mBTService!=null && mBTService.IsOpen()) {
			GetBluePrinterLists();
		}else {
			OpenDevice();
		}
		
	}

	private void GetBluePrinterLists()
	{
		CharSequence[] entries;
		Set<BluetoothDevice> devices  =  mBTService.GetBondedDevice();
		if (devices.size() > 0) {
			entries = new CharSequence[devices.size()] ;
			int i =0 ; 
			for (BluetoothDevice device : devices) {
				entries[i++] = (device.getName() + "\n" + device.getAddress());
			}
		}else {
			entries = new CharSequence[1];
			entries[0] = "没有可用打印机, 请重新扫描!";
		}	
		ListPreference lp = (ListPreference)findPreference("title_form_setting_btn_printer_list");
		lp.setEntries(entries);
		lp.setEntryValues(entries);
	}

	private void OpenDevice()
	{
		if (!mBTService.HasDevice()) {
			Utility.MessageBox(Actual_System_Setting.this,"请打开蓝牙连接器!");
		}else {
			if(mBTService.IsOpen())
			{
				Utility.MessageBox(Actual_System_Setting.this,"已经打开");

			}else {
				mBTService.OpenDevice();
			}
		}
	}
	
	@Override
	@Deprecated
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		Intent intent;
		String key = preference.getKey();
		if (key.equals("title_form_setting_btn_printer_open")) {
			OpenDevice();
		}else if (key.equals("title_form_setting_btnupload")) {
        	AdminPicForceHandlerTask task = new AdminPicForceHandlerTask();
        	task.start();
		}else if (key.equals("title_form_setting_btn_printer_close")) {
			if (mBTService.getState() == mBTService.STATE_CONNECTED) {
				mBTService.DisConnected();
			}
			mBTService.CloseDevice();
		}
//		else if (key.equals("title_form_setting_btn_printer_connectprinter")) {
//			String printerInfo = sp.getString("title_form_setting_btn_printer_list", "");
//			if (printerInfo.contains("没有可用打印机, 请重新扫描!")) {
//				Utility.MessageBox( Actual_System_Setting.this,printerInfo );
//			}else if (printerInfo.equals("")) {
//				Utility.MessageBox(Actual_System_Setting.this,"请先选择匹配打印机");
//			}else{
//				String[] dev = printerInfo.split("\n");
//				ConnectPrinter(dev[1]);
//			}
//		}
//		else if (key.equals("title_form_setting_btn_printer_rescan")) {
//            Intent serverIntent = new Intent(this, DeviceListActivity.class);
//            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
//		}
//		else if (key.equals("title_form_setting_btn_printer_blackline")) {
//			if (mBTService.getState() == mBTService.STATE_CONNECTED) {
//				mBTService.PrintCharacters("\n");
//			}
//		}else if (preference.getKey().equals("title_form_setting_btn_camera")) {
			//intent = new Intent( Actual_System_Setting.this, MyPreferenceActivity.class);
			//this.startActivity(intent);
//		}
//		else if (preference.getKey().equals("title_form_setting_btn_printer")) {
//            Intent serverIntent = new Intent(this, DeviceListActivity.class);
//            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
//		}
		else if (preference.getKey().equals("title_form_setting_table_car_setting")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_WAIZUSHILUN);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_car_setting));
			this.startActivity(intent);
		}else if (preference.getKey().equals("title_form_setting_table_resource_2")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_WAIZUJIXIE);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_jixie_setting));
			this.startActivity(intent);
		}else if (preference.getKey().equals("title_form_setting_table_resource_3")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_ZIYOUSHILUN);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_cailiao_setting));
			this.startActivity(intent);	
		}else if (preference.getKey().equals("title_form_setting_table_resource_5")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_GONYINGSHANG);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_cailiao_setting));
			this.startActivity(intent);	
		}else if (preference.getKey().equals("title_form_setting_table_resource_6")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_CAILIAOMINGCHENG);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_cailiao_setting));
			this.startActivity(intent);
		}else if (preference.getKey().equals("title_form_setting_table_resource_7")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_ZHUANGDI);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_cailiao_setting));
			this.startActivity(intent);	
		}else if (preference.getKey().equals("title_form_setting_table_resource_8")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_XIEDI);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_cailiao_setting));
			this.startActivity(intent);		
		}else if (preference.getKey().equals("title_form_setting_table_resource_chexing")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_CHEXING);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_cailiao_setting));
			this.startActivity(intent);		
		}
		else if (preference.getKey().equals("title_form_setting_table_resource_didian")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_DIDIAN);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_cailiao_setting));
			this.startActivity(intent);		
		}
		else if (preference.getKey().equals("title_form_setting_table_resource_siji")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_SIJI);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_cailiao_setting));
			this.startActivity(intent);		
		}else if (preference.getKey().equals("title_form_setting_table_resource_allchepai")) {
			intent = new Intent( this, Actual_Form_Car_Setting.class);
			intent.putExtra("T_Name", Submit_System_Setting_Data_Task.T_ALLCHEPAI);
			intent.putExtra("mTitle", getResources().getString(R.string.title_actual_form_cailiao_setting));
			this.startActivity(intent);		
		}else if (preference.getKey().equals("title_form_setting_btnupdate")) {
			SubmitUpdateTask mSubmitTask = new SubmitUpdateTask();
			mSubmitTask.setListener(mTaskListener_UpdateFile);
			TaskParams params = new TaskParams();
			params.put(SubmitUpdateTask.UPDATEFILE, 
					MainApplication.updatefile);
			
			mSubmitTask.execute(params);
		}else if (key.equals("title_form_setting_table_autodatasy")) {
			//GetErpDictList(Submit_System_Setting_Data_Task.T_WAIZUSHILUN, "DictContent");
//			GetErpDictList(Submit_System_Setting_Data_Task.T_WAIZUJIXIE, "DictContent");
			GetErpDictList(Submit_System_Setting_Data_Task.T_ZIYOUSHILUN, "DictContent");
//			GetErpDictList(Submit_System_Setting_Data_Task.T_GONYINGSHANG, "DictContent");
//			GetErpDictList(Submit_System_Setting_Data_Task.T_CAILIAOMINGCHENG, "DictContent");
//			GetErpDictList(Submit_System_Setting_Data_Task.T_ZHUANGDI, "DictContent");
//			GetErpDictList(Submit_System_Setting_Data_Task.T_XIEDI, "DictContent");
			//GetErpDictList(Submit_System_Setting_Data_Task.T_CHEXING, "DictContent");
//			GetErpDictList(Submit_System_Setting_Data_Task.T_DIDIAN, "DictContent");
//			GetErpDictList(Submit_System_Setting_Data_Task.T_SIJI, "DictContent");
//			GetErpDictList(Submit_System_Setting_Data_Task.T_ALLCHEPAI, "CarPaiHao");
		}else if (key.equals("title_form_piaoju")) {
			intent = new Intent( this, FinishedListActivity.class);
			startActivity(intent);
		}
		return super.onPreferenceTreeClick(preferenceScreen, preference);
		
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                ConnectPrinter(address);
            }
            break;
        }
    }
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
	
	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	private Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			SUCCESS_CONNECT = false;
			switch (msg.what) {
			case MESSAGE_STATE_CHANGE:// 蓝牙连接状态
				switch (msg.arg1) {
				case BlueToothService.STATE_CONNECTED:// 
					Utility.MessageBox(Actual_System_Setting.this,"已经连接");
					break;
				case BlueToothService.STATE_CONNECTING:
					Utility.MessageBox(Actual_System_Setting.this,"正在连接打印机");
					break;
				case BlueToothService.STATE_LISTEN:
				case BlueToothService.STATE_NONE:
					break;
				case BlueToothService.SUCCESS_CONNECT:
					SUCCESS_CONNECT = true;
					Utility.MessageBox(Actual_System_Setting.this,"已经成功连接打印机");
					break;
				case BlueToothService.FAILED_CONNECT:
					Utility.MessageBox(Actual_System_Setting.this,"连接打印机失败");
					break;
				case BlueToothService.LOSE_CONNECT:
					Utility.MessageBox(Actual_System_Setting.this,"打印机已掉线!");
					break;
				}
				break;
			case MESSAGE_READ:
				// sendFlag = false;//缓冲区已满
				break;
			case MESSAGE_WRITE:// 缓冲区未满
				// sendFlag = true;
				break;

			}
		}
	};
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
//		if(key.equals("title_form_setting_btn_printer_list")){   
//			ConnectPrinter();
//		}
	}
	
	private void ConnectPrinter( String ScanAddress) {
		// 获取蓝牙物理地址
		if (!mBTService.IsOpen()) {// 判断蓝牙是否打开
			mBTService.OpenDevice();
			return;
		}
		if (mBTService.GetScanState() == mBTService.STATE_SCANING) {
			Message msg = new Message();
			msg.what = 2;
			mhandler.sendMessage(msg);
		}
		if (mBTService.getState() == mBTService.STATE_CONNECTING) {
			return;
		}
		Utility.MessageBox(Actual_System_Setting.this,"连接打印机");
		mBTService.DisConnected();
		mBTService.ConnectToDevice(ScanAddress);// 连接蓝牙
	}
	
	private TaskListener mTaskListener_UpdateFile = new TaskAdapter() {
		public ProgressDialog mDialog;
		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {
			mDialog.dismiss();
			SubmitUpdateTask t = (SubmitUpdateTask)task;
			if (result == TaskResult.OK) {
				UpdateManager manager = new UpdateManager(Actual_System_Setting.this);
				// 检查软件更新
				manager.UPDATEFILE = MainApplication.updatefile;
				manager.checkUpdate();
			} else {
				Utility.MessageBox(Actual_System_Setting.this,t.getMsg());
			}
		}

		@Override
		public void onCancelled(GenericTask task) {
			mDialog.dismiss();
			mDialog = null;
		}

		@Override
		public void onPreExecute(GenericTask task) {
			mDialog = Utility.ShowModelDialog(Actual_System_Setting.this, getString(R.string.setting_system_update));
			mDialog.show();
		}
	};	
	
	public void GetErpDictList(String Type, String Value) {
		if (LoginActivity.pmUser.UserName!=null) {
			Submit_System_Setting_Data_Task mSubmitTask = new Submit_System_Setting_Data_Task();
			mSubmitTask.setListener(mTaskListener);
			TaskParams params;
			params = new TaskParams();
			//params.put(Submit_System_Setting_Data_Task.TYPENAME,Submit_System_Setting_Data_Task.T_ERPUSER);
			params.put(Submit_System_Setting_Data_Task.TYPENAME , Type );
			params.put(Submit_System_Setting_Data_Task.FIELD , Value );
			params.put(Submit_System_Setting_Data_Task.TYPECODE, LoginActivity.pmUser.UserName);
			
			mSubmitTask.execute(params);
		}
	}
	
	private TaskListener mTaskListener = new TaskAdapter() {
		private ProgressDialog mDialog;
		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {
			if (mDialog!=null) {
				mDialog.dismiss();
				mDialog = null;
			}

			Submit_System_Setting_Data_Task t = (Submit_System_Setting_Data_Task)task;
			if (result == TaskResult.OK) {
				JSONArray jsonArray = t.pJsonArray;
				String s="";
				try {
					if (t.sField.equals("CarPaiHao")) { //车牌号报销 特殊处理
						for(int i = 0 ; i < jsonArray.length(); i ++)
						{
							s +=jsonArray.getJSONObject(i).getString( t.sField) + "\n"; 
						}
					}else {
						s = jsonArray.getJSONObject(0).getString( t.sField);	
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				MainApplication.pShareUtil.WriteParam(t.pTypeName, s);
				InitGoldelData();
				//editor = getSharedPreferences(FILENAME, MODE_WORLD_WRITEABLE).edit();
				//editor.putString(t.pTypeName, jsonArray.toString());
				Utility.MessageBox(Actual_System_Setting.this,t.pTypeName + getString(R.string.setting_success_system_data));
			} else {
				Utility.MessageBox(Actual_System_Setting.this,t.mErrorMessage);
			}
		}

		@Override
		public void onCancelled(GenericTask task) {
			mDialog.dismiss();
			mDialog = null;
		}

		@Override
		public void onPreExecute(GenericTask task) {
			if (mDialog==null) {
				mDialog = Utility.ShowModelDialog(Actual_System_Setting.this, getString(R.string.setting_system_update));
				mDialog.show();
			}
		}
	};
	
}